package thong.servlet;

import java.io.IOException;
import java.util.SortedMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.sql.Result;

import thong.util.JdbcUtil;

/**
 * Servlet implementation class ProductCRUDServlet
 */
@WebServlet("/ProductCRUD.do")
public class ProductCRUDServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductCRUDServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		/*
		 *  nhận tham số từ form nhập
		 */
		String Id = request.getParameter("txtId");
		String Name = request.getParameter("txtName");
		String ProductDate = request.getParameter("txtProDuctDate");
        String Picture = request.getParameter("txtPicture");
        String Discount = request.getParameter("txtDiscount");
		String Special = request.getParameter("rdoSpecial");
		String Quantity = request.getParameter("txtQuantity");
        String CategoryId = request.getParameter("txtCategoryId");


        /* 
         * Làm việc với CSDL khi tồn tài các tham số điều khiển tương 
         * ứng (btnInsert, btnUpdate, btnDelete, btnSelect, btnSearch)
         */
        try{
	        if(request.getParameter("btnInsert") != null){
		        String sql = "INSERT INTO Products(Name, ProductDate, Picture,Discount,Special,Quantity,CategoryId) VALUES(?,?,?,?,?,?,?)";
		        JdbcUtil.executeUpdate(sql,Name, ProductDate, Picture,Discount,Special,Quantity,CategoryId);
		        request.setAttribute("errors", "Inserted successfully !");
	        }
	        else if(request.getParameter("btnUpdate") != null){
	        	String sql = "UPDATE Products SET Name=?, ProductDate=?, Picture=?,Discount=?,Special=?,Quantity=?,CategoryId=? WHERE Id=?";
		        JdbcUtil.executeUpdate(sql,Name, ProductDate, Picture,Discount,Special,Quantity,CategoryId,Id);
		        request.setAttribute("errors", "Updated successfully !");
	        }
	        else if(request.getParameter("btnDelete") != null){
		        String sql = "DELETE FROM Products WHERE Id=?";
		        JdbcUtil.executeUpdate(sql, Id);
		        request.setAttribute("errors", "Deleted successfully !");
	        }
	        //xu ly edit
	        else if(request.getParameter("lnkEdit") != null){
		        String sql = "SELECT * FROM Products WHERE Id=?";
		        /*
		         * Truy vấn và chia sẻ kết quả trong request
		         */
		        //String id1=request.getParameter("lnkEdit");
		        Result result = JdbcUtil.toResult(sql, Id);
		        @SuppressWarnings("rawtypes")
				SortedMap pro = result.getRows()[0];
		        request.setAttribute("pro", pro);
		        request.setAttribute("errors", "Loaded successfully !");
	        }
        }
        catch (Exception e) {
        	request.setAttribute("errors", "Data manipilation error !");
        	//request.setAttribute("errors", "loi haha" + ProductDate);
        	//request.setAttribute("errors", e.getMessage());
		}
        /*
         * Duy trì chuỗi tìm kiếm của câu lệnh sql trong session
         */
        HttpSession session = request.getSession();
        if(request.getParameter("btnSearch") != null){
        	session.setAttribute("search", request.getParameter("txtSearch"));
        }
        else if(session.getAttribute("search") == null){
        	session.setAttribute("search", "");
        }
        String search = (String)session.getAttribute("search");
        
        /*
         * Tìm kiếm theo tên và chia sẽ kết quả trong request
         */
        String searchSql = "SELECT * FROM Products  WHERE Name LIKE ?";
        Result prod = JdbcUtil.toResult(searchSql, "%" + search + "%");
        request.setAttribute("prod", prod);
        /*
         * Chuyển tiếp sang trang ManagerProduct.jsp
         */
       // request.getRequestDispatcher("CustomerCRUD.jsp").forward(request, response);
        request.getRequestDispatcher("pages/ManagerProduct.jsp").forward(request, response);
	}

}
